package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public String login(User user) {
        //1.将密码加密
        String password =
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        //
       User userDB=userMapper.findUserByUP(user);
       if (userDB==null){
           //用户名或者密码错误,返回token应该为空
           return null;
       }
       //密码正确,生成token 要求token不能重复
       String token = UUID.randomUUID().toString();
       //将token存入redis
       //userMapper.updateToken(userDB.getId(),token);
       return token;

    }

    @Override
    public PageResult findUserList(PageResult pageResult) {
        //1.获取当前页
        int size  = pageResult.getPageSize();
        //2.获取当前页的起始行
        int startNum= (pageResult.getPageNum()-1)*size;
        String query=pageResult.getQuery();
        List<User> userList=
                userMapper.findUserList(startNum,size,query);
        //获取总记录数
        long total = userMapper.findUserCount(query);
        //将分页数据进行数据封装
        pageResult.setTotal(total).setRows(userList);
        return pageResult;
    }

    @Override
    @Transactional//如果抛出异常,事务回滚
    public void updateStatus(User user) {
        //1.获取当前时间
        Date date = new Date();
        user.setUpdated(date);
        //2.调用mapper
        userMapper.updateStatus(user);

    }
/*
* 业务思维：
* 1.查询用户信息
* 2.更新用户信息
* 3.更新用户的登录时间
*4.密码加密（md5）
* 5.更新用户的token
* 6.更新用户的登录时间
* 7.更新用户的登录状态 正常 true
* 注意：事务回滚
* */
    @Transactional
    @Override
    public void addUser(User user) {
        //1.获取当前时间
        Date date = new Date();
        user.setCreated(date);
        user.setUpdated(date);
        //3.将密码加密
        String password =
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        //4.设定用户的登录状态
        user.setStatus(true);
       userMapper.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }
    @Transactional
    @Override
    public void updateUser(User user) {
        //1.获取当前时间
        Date date = new Date();
        user.setUpdated(date);
        //2.调用mapper
        userMapper.updateUser(user);

    }
@Transactional
    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
}
